<?php


namespace App\Http\Controllers;


use App\Internals\CourseInternal;
use App\Models\Level;
use App\Models\LevelWord;
use App\Models\UserCourse;
use App\Models\UserLesson;
use App\Models\UserStatus;

class LevelController extends Controller
{
    /*
     * @api get /study-api/levels/words 获取等级评测单词
     * @version 0.0.1
     * @group web
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{}
     * }
     */
    public function words()
    {
        $wordsObj = LevelWord::all();
        $result = [];
        /** @var LevelWord $wordObj */
        foreach ($wordsObj as $wordObj) {
            $result[] = [
                'id' => $wordObj->getId(),
                'en' => $wordObj->getWord(),
                'cn' => $wordObj->getChinese()
            ];
        }
        shuffle($result);
        return $this->sendSuccessJson($result);
    }

    /*
     * @api post /study-api/levels/test 等级评估
     * @version 0.0.1
     * @group web
     *
     * @param body array wordIds 单词ID
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{}
     * }
     */
    public function test()
    {
        $this->validate($this->request, [
            'wordIds' => 'array'
        ]);
        $wordIds = $this->request->input('wordIds');
        $level = 1;
        if ($wordIds) {
            $levelsObj = Level::orderBy('level', 'desc')->get();
            /** @var Level $levelObj */
            foreach ($levelsObj as $levelObj) {
                $levelWordIds = LevelWord::where('level', $levelObj->getLevel())->pluck('id')->toArray();
                $selectedLevelWordIds = array_intersect($levelWordIds, $wordIds);
                $rate = round(count($selectedLevelWordIds) * 100 / count($levelWordIds));
                if ($rate >= $levelObj->getRate()) {
                    if ($levelObj->getLevel() == Level::MAX_LEVEL) {
                        $level =  $levelObj->getLevel();
                    } else {
                        $level = $levelObj->getLevel() + 1;
                    }
                    break;
                }
            }
        }
        /** @var UserStatus $statusObj */
        $statusObj = UserStatus::where('user_id', $this->userId)->first();
        $statusObj->setTestLevel($level);
        $statusObj->save();
        $result = [
            'level' => $level,
        ];

        return $this->sendSuccessJson($result);
    }

    /*
     * @api get /study-api/levels/{level}/sample 获取等级试读课
     * @version 0.0.1
     * @group web
     *
     * @param path int level 等级
     *
     * @response 200 正常结果 {
     *  "code":0,
     *  "msg":"",
     *  "data":{}
     * }
     *
     */
    public function sample($level)
    {
        // 等级的第一节课是试读课
        $course = CourseInternal::getLevelFirstLesson($level);
        // 评测进来，用户未购买
        $userCourseObj = UserCourse::ofUserCourse($this->userId, $course['courseId'])->first();
        if (!$userCourseObj) {
            $courseObj = new UserCourse();
            $courseObj->setUserId($this->userId);
            $courseObj->setOrderId(0);
            $courseObj->setLevel($level);
            $courseObj->setCourseId($course['courseId']);
            $courseObj->setStatus(UserCourse::IS_FALSE);
            $courseObj->save();
        }

        if(!UserLesson::ofUserLesson($this->userId, $course['firstLessonId'])->exists()) {
            $lessonObj = new UserLesson();
            $lessonObj->setUserId($this->userId);
            $lessonObj->setLessonId($course['firstLessonId']);
            $lessonObj->setCourseId($course['courseId']);
            $lessonObj->setSequence($course['sequence']);
            $lessonObj->setWordCount($course['wordCount']);
            $lessonObj->setKnowledgeCount($course['knowledgeCount']);
            $lessonObj->setEssenceQaCount($course['essenceQaCount']);
            $lessonObj->setGameTestCount($course['gameTestCount']);
            $lessonObj->setGameWordCount($course['gameWordCount']);
            $lessonObj->setEnableTime($this->nowTimestamp());
            $lessonObj->save();
        }
        $data = [
            'lessonId' => $course['firstLessonId']
        ];
        return $this->sendSuccessJson($data);
    }
}
